{% extends "base.html" %}

{% block title %}Live Builds{% endblock %}

{% block content %}

     {% for build in builds %}
    <div style="float: left; width: {{ build_percent }}%;">
        <h3>{{ build.project }}</h3>
        <pre class="build-output"><span id="build-output-{{ build.id }}">{{ build.output }}</span></pre>
    </div>
    {% endfor %}
    <form id="form" style="display: none;">
        <input type="submit">
    </form>
{% endblock %}

{% block extra_scripts %}
{{ block.super }}

  <script type="text/javascript">
    $(function() {
        var WS = false;
        if (window.WebSocket) WS = WebSocket;
        if (!WS && window.MozWebSocket) WS = MozWebSocket;
        if (!WS)
            alert('Your browser does not seem to support Websockets.');

        var $results = $('#results');
        var $form = $('#form');

        var ws = new WS('ws://{{ WEBSOCKET_HOST }}/websocket');
        ws.send_json = function(data) {
            this.send(JSON.stringify(data));
        }
        ws.onopen = function() {
            console.log('websocket connected');
            $form.submit()
        };
        ws.onerror = function(evt) {
            console.log('error');
            console.log(evt.data);
        };
        ws.onmessage = function(message) {
            console.log(message);
            var data = JSON.parse(message.data);
            switch (data.cmd) {
                case 'status':
                    $build_output = $('#build-output-' + data.id);
                    $build_output.append(data.status);
                    window.scrollBy(0,50);
                    break;
                case 'result':
                    console.log(data.result);
                    var result = data.result;
                    var $result = $('<tr/>')
                    $result.append($('<td>' + result.status_code + '</td>'))
                    $result.append($('<td>' + result.url + '</td>'))
                    $result.append($('<td>' + result.length + '</td>'))
                    $result.append($('<td>' + (result.duration*1000) + '</td>'))
                    $results.append($result);
                    break;
            }
        };
        ws.onclose = function() {
            console.log('websocket closed');
        };
        $form.bind('submit', function(e) {
            e.preventDefault();
            //var url = $url.val();
            {% for build in builds %}
            ws.send_json({id: '{{ build.id }}', cmd: 'tail', url: '{{ build.id }}'});
            {% endfor %}
            //$form.hide()
        });
    });

  </script>
{% endblock %}
